<template>
  <!-- ASN单表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="80%"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="150"
      >
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>

        <div class="search-container">
          <el-row>
            <el-col :span="8">
              <el-form-item label="订单编号" prop="orderNo">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.orderNo"
                  placeholder="请输入订单编号"
                  clearable
                />
                <span v-else>{{ formData.orderNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工厂" prop="plantId" required>
                <el-select
                  v-if="!props.isReadonly"
                  @change="plantChange"
                  v-model="formData.plantId"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in plants"
                    :key="item.id"
                    :label="item.organizationName"
                    :value="item.id"
                  />
                </el-select>
                <span v-else
                  >{{ formData.plantName }} ({{ formData.plantCode }})</span
                >
              </el-form-item></el-col
            >
            <el-col :span="8">
              <el-form-item label="送货单号" prop="asnCode">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.asnCode"
                  placeholder="请输入送货单号"
                  clearable
                />
                <span v-else>{{ formData.asnCode }}</span>
              </el-form-item></el-col
            >
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="供应商" prop="partnerId" required>
                <el-select
                  v-if="!props.isReadonly"
                  @change="partnerChange"
                  v-model="formData.partnerId"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in partners"
                    :key="item.id"
                    :label="item.partnerName"
                    :value="item.id"
                  />
                </el-select>
                <span v-else
                  >{{ formData.partnerName }}({{ formData.partnerCode }})</span
                >
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="送货日期" prop="asnDate">
                <template v-if="!props.isReadonly">
                  <el-date-picker
                    v-model="formData.asnDate"
                    type="date"
                    placeholder="请选择送货日期"
                    style="width: 192px"
                    clearable
                  />
                </template>
                <template v-else>
                  <span>{{ formData.asnDate }}</span>
                </template>
              </el-form-item></el-col
            >
            <el-col :span="8">
              <el-form-item label="预计到货日期" prop="arriveDate">
                <template v-if="!props.isReadonly">
                  <el-date-picker
                    v-model="formData.arriveDate"
                    type="date"
                    placeholder="请选择预计到货日期"
                    style="width: 192px"
                    clearable
                  />
                </template>
                <template v-else>
                  <span>{{ formData.arriveDate }}</span>
                </template>
              </el-form-item></el-col
            >
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="运输方式" prop="modeTransport">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.modeTransport"
                  placeholder="请输入运输方式"
                  clearable
                />
                <span v-else>{{ formData.modeTransport }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="运单号" prop="trackingNumber">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.trackingNumber"
                  placeholder="请输入运单号"
                  clearable
                />
                <span v-else>{{ formData.trackingNumber }}</span>
              </el-form-item></el-col
            >
            <el-col :span="8">
              <el-form-item label="承运人" prop="carrier">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.carrier"
                  placeholder="请输入承运人"
                  clearable
                />
                <span v-else>{{ formData.carrier }}</span>
              </el-form-item></el-col
            >
          </el-row>

          <!-- <el-form-item
            label="存储地点编号;要货地点"
            prop="storageLocationCode"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.storageLocationCode"
              placeholder="请输入存储地点编号;要货地点"
              clearable
            />
            <span v-else>{{ formData.storageLocationCode }}</span>
          </el-form-item> -->
          <el-row>
            <el-col :span="8"
              ><el-form-item label="发货联系人" prop="shippingContactPerson">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.shippingContactPerson"
                  placeholder="请输入发货联系人"
                  clearable
                />
                <span v-else>{{ formData.shippingContactPerson }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发货联系人电话" prop="shippingContactPhone">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.shippingContactPhone"
                  placeholder="请输入发货联系人电话"
                  clearable
                />
                <span v-else>{{ formData.shippingContactPhone }}</span>
              </el-form-item></el-col
            >
            <el-col :span="8"
              ><el-form-item label="车牌号" prop="plateNumber">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.plateNumber"
                  placeholder="请输入车牌号"
                  clearable
                />
                <span v-else>{{ formData.plateNumber }}</span>
              </el-form-item></el-col
            >
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="发货状态" prop="shipmentStatus">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.shipmentStatus"
                  clearable
                  placeholder="请选择发货状态"
                >
                  <el-option
                    v-for="item in dictionaryStore.filterDictList(
                      'ShipmentStatus'
                    )"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{
                  dictionaryStore.filterDictName(
                    "ShipmentStatus",
                    formData.shipmentStatus
                  )
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8"
              ><el-form-item label="备注" prop="remarks">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                  clearable
                />
                <span v-else>{{ formData.remarks }}</span>
              </el-form-item></el-col
            >
          </el-row>
        </div>
        <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button type="success" plain @click="handleAdd">
              <i-ep-plus />
              新增</el-button
            >
          </template>
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="100"
              />
              <!-- <el-table-column label="订单ID" props="orderId" min-width="150">
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.orderId'"
                    :rules="rules.sonorderId"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.orderId"
                      placeholder="请输入订单ID"
                      clearable
                    />
                    <span v-else>{{ row.orderId }}</span>
                  </el-form-item>
                </template>
              </el-table-column> -->

              <!-- <el-table-column
                label="箱标签号"
                props="unitBarcode"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.unitBarcode'"
                    :rules="rules.sonunitBarcode"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.unitBarcode"
                      placeholder="请输入箱标签号"
                      clearable
                    />
                    <span v-else>{{ row.unitBarcode }}</span>
                  </el-form-item>
                </template>
              </el-table-column> -->

              <el-table-column
                label="物料号"
                props="materialCode"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.materialCode'"
                    :rules="rules.sonmaterialCode"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      @change="() => materialChange(row)"
                      v-model="row.materialCode"
                      placeholder="请选择物料号"
                      clearable
                    >
                      <el-option
                        v-for="item in materials"
                        :key="item.id"
                        :label="item.materialCode"
                        :value="item.materialCode"
                      />
                    </el-select>
                    <span v-else>{{ row.materialCode }}</span>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                label="生产批次"
                props="supplyBatch"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.supplyBatch'"
                    :rules="rules.sonsupplyBatch"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.supplyBatch"
                      placeholder="请输入生产批次"
                      clearable
                    />
                    <span v-else>{{ row.supplyBatch }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="包装容量"
                props="quantity"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.quantity'"
                    :rules="rules.sonquantity"
                    label-width="0"
                  >
                    <el-input-number
                      v-if="!props.isReadonly"
                      v-model="row.quantity"
                      placeholder="请输入包装容量"
                      clearable
                      :min="1"
                    />
                    <span v-else>{{ row.quantity }}</span>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                label="数量单位"
                props="quantityUnit"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.quantityUnit'"
                    :rules="rules.sonquantityUnit"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.quantityUnit"
                      placeholder="请输入数量单位"
                      clearable
                    />
                    <span v-else>{{ row.quantityUnit }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="备注" props="remarks" min-width="150">
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.remarks'"
                    :rules="rules.sonremarks"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.remarks"
                      placeholder="请输入备注"
                      clearable
                    />
                    <span v-else>{{ row.remarks }}</span>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="90"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SRMSRMASNADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
let plants = ref([]);
let materials = ref([]);
let partners = ref([]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    partners.value = [];
    materials.value = [];
    getPlants();

    if (newVal === true) {
      setTimeout(() => {
        formRef.value.clearValidate();
      }, 50);
    }
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  orderNo: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  asnCode: "",
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  asnDate: "",
  arriveDate: "",
  modeTransport: "",
  trackingNumber: "",
  storageLocationId: "",
  storageLocationCode: "",
  storageLocationName: "",
  carrier: "",
  shippingContactPerson: "",
  shippingContactPhone: "",
  plateNumber: "",
  shipmentStatus: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  details: [
    {
      id: "",
      asnId: "",
      orderId: "",
      materialDetailId: "",
      unitBarcode: "",
      materialId: "",
      materialCode: "",
      materialName: "",
      supplyBatch: "",
      quantity: "",
      isreceive: "",
      quantityUnit: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      deleted: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  orderNo: [{ required: true, message: "请输入订单编号", trigger: "blur" }],
  organizationId: [
    { required: true, message: "请输入公司ID;基本信息", trigger: "blur" },
  ],
  organizationCode: [
    { required: true, message: "请输入公司代码;基本信息", trigger: "blur" },
  ],
  organizationName: [
    { required: true, message: "请输入公司名称;基本信息", trigger: "blur" },
  ],
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  plantCode: [{ required: true, message: "请输入工厂代码", trigger: "blur" }],
  plantName: [{ required: true, message: "请输入工厂名称", trigger: "blur" }],
  asnCode: [{ required: true, message: "请输入送货单号", trigger: "blur" }],
  partnerId: [{ required: true, message: "请选择供应商", trigger: "change" }],
  partnerCode: [
    { required: true, message: "请输入供应商编号", trigger: "blur" },
  ],
  partnerName: [
    { required: true, message: "请输入供应商名称", trigger: "blur" },
  ],
  asnDate: [{ required: true, message: "请输入送货日期", trigger: "blur" }],
  arriveDate: [
    { required: true, message: "请输入预计到货日期", trigger: "blur" },
  ],

  shipmentStatus: [
    { required: true, message: "请输入发货状态", trigger: "blur" },
  ],

  createTime: [{ required: true, message: "请输入创建时间", trigger: "blur" }],
  createdUserId: [{ required: true, message: "请输入创建人", trigger: "blur" }],
  createdUserName: [
    { required: true, message: "请输入创建人名", trigger: "blur" },
  ],
  lastUpdateTime: [
    { required: true, message: "请输入更新时间", trigger: "blur" },
  ],
  lastUpdatedUserId: [
    { required: true, message: "请输入更新人", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { required: true, message: "请输入更新人名", trigger: "blur" },
  ],
  deleted: [{ required: true, message: "请输入是否删除", trigger: "blur" }],
  sonasnId: [{ required: true, message: "请输入ASN单ID", trigger: "blur" }],
  sonorderId: [{ required: true, message: "请输入订单ID", trigger: "blur" }],
  sonmaterialDetailId: [
    { required: true, message: "请输入ASN关联的物料信息表ID", trigger: "blur" },
  ],
  sonunitBarcode: [
    { required: true, message: "请输入箱标签号", trigger: "blur" },
  ],
  sonmaterialId: [{ required: true, message: "请输入物料id", trigger: "blur" }],
  sonmaterialCode: [{ required: true, message: "请选择物料", trigger: "blur" }],
  sonmaterialName: [
    { required: true, message: "请输入物料名称", trigger: "blur" },
  ],
  sonsupplyBatch: [
    { required: true, message: "请输入生产批次", trigger: "blur" },
    { validator: validateEndTime, trigger: "change" },
  ],
  sonquantity: [
    { required: true, message: "请输入包装容量", trigger: "blur" },
    { validator: quantity, trigger: "change" },
  ],
  sonisreceive: [
    { required: true, message: "请输入是否收货", trigger: "blur" },
  ],
  sonquantityUnit: [
    { required: true, message: "请输入数量单位", trigger: "blur" },
  ],
  sonremarks: [{ required: true, message: "请输入备注", trigger: "blur" }],
  soncreateTime: [
    { required: true, message: "请输入创建时间", trigger: "blur" },
  ],
  soncreatedUserId: [
    { required: true, message: "请输入创建人", trigger: "blur" },
  ],
  soncreatedUserName: [
    { required: true, message: "请输入创建人名", trigger: "blur" },
  ],
  sonlastUpdateTime: [
    { required: true, message: "请输入更新时间", trigger: "blur" },
  ],
  sonlastUpdatedUserId: [
    { required: true, message: "请输入更新人", trigger: "blur" },
  ],
  sonlastUpdatedUserName: [
    { required: true, message: "请输入更新人名", trigger: "blur" },
  ],
  sondeleted: [{ required: true, message: "请输入是否删除", trigger: "blur" }],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};

const details = {
  id: "",
  asnId: "",
  orderId: "",
  materialDetailId: "",
  unitBarcode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  supplyBatch: "",
  quantity: "",
  isreceive: "",
  quantityUnit: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
      getPlants();
      getOrganization();
      getPartners();
      getMaterials();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [details];
  formData.id = "";
  formData.orderNo = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.asnCode = "";
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.partnerName = "";
  formData.asnDate = "";
  formData.arriveDate = "";
  formData.modeTransport = "";
  formData.trackingNumber = "";
  formData.storageLocationId = "";
  formData.storageLocationCode = "";
  formData.storageLocationName = "";
  formData.carrier = "";
  formData.shippingContactPerson = "";
  formData.shippingContactPhone = "";
  formData.plateNumber = "";
  formData.shipmentStatus = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
}

const loading = ref(false);
async function getPlants() {
  const data = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data.data;
  console.log(plants.value);
}
async function getPartners() {
  const data = await request({
    url: "/srm/srmasn/getList1",
    method: "post",
    data: { organizationId: formData.organizationId },
  });
  partners.value = data.data;
  console.log(partners.value);
}
async function getMaterials() {
  const data = await request({
    url: `/srm/srmasn/getList2/` + formData.partnerId,
    method: "get",
    data: {},
  });
  materials.value = data.data;
  console.log(materials.value);
}
async function getOrganization() {
  const data = await request({
    url: `/system/sysOrganization/get/${formData.organizationId}`,
    method: "post",
    data: {},
  });
  formData.organizationCode = data.data.organizationCode;
  formData.organizationName = data.data.organizationName;
  console.log(formData.organizationName);
}

function partnerChange() {
  var partner = partners.value.find((item) => {
    return item.id === formData.partnerId;
  });

  formData.partnerCode = partner.partnerCode;
  formData.partnerName = partner.partnerName;
  getMaterials();
}

function materialChange(row) {
  if (row && row.materialCode && materials.value) {
    var material = materials.value.find(
      (item) => item.materialCode === row.materialCode
    );
    if (material) {
      row.materialId = material.materialId; // 更新当前行的materialId
      row.materialName = material.materialName; // 更新当前行的materialName
    }
  }
}
function plantChange() {
  var plant = plants.value.find((item) => {
    return item.id === formData.plantId;
  });

  formData.plantCode = plant.organizationCode;
  formData.plantName = plant.organizationName;
  formData.organizationId = plant.parentId;
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.partnerName = "";
  getOrganization();
  getPartners();
}
/** ASN单保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/srm/srmasn/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
function validateEndTime(rule, value, callback) {
  const dateFormat = /^\d{8}$/; // 正则表达式，验证是否为八位数字字符串
  if (!dateFormat.test(value)) {
    callback(new Error("符合 (yyyyMMdd)格式"));
  } else {
    callback();
  }
}
function quantity(rule, value, callback) {
  if (value < 1) {
    callback(new Error("包装容量必须大于等于1"));
  } else {
    callback();
  }
}
async function getdetails() {
  let sondetails = await request({
    url: "/srm/srmasn/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}
:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
</style>
